using UnityEngine;

namespace GameFrameWork
{
    public partial class UIReuseContainer : IVirtualLayoutElement
    {
        Vector2 _anchor;
        Vector2 _anchoredPosition;
        Vector2 _sizeDelta;
        Vector2 _pivot;
        Vector3 _localScale = Vector3.one;
        Vector3 _localEulerAngles;

        static Vector3[] corners = new Vector3[4];
        [SerializeField] Bounds _bound;
        public Bounds Bound => _bound;


        readonly RectTransform content;
        readonly RectTransform viewport;

        public UIReuseContainer(int dataIndex, UIReuseList reuselist, IUIReuseItemCtrl ctrl, IResModule resModule,
            RectTransform content,
            RectTransform viewport) : this(dataIndex, reuselist, ctrl, resModule)
        {
            this.content = content;
            this.viewport = viewport;
        }


        public void CalculateTransformation(RectTransform template)
        {
            _anchoredPosition = Vector2.zero;
            _anchor = Vector2.up;
            _pivot = template.pivot;
            _sizeDelta = template.sizeDelta;
            _localScale = template.localScale;
            _localEulerAngles = template.localEulerAngles;
        }

        public Vector2 GetAnchoredPosition()
        {
            return _anchoredPosition;
        }

        public Vector2 GetPosition()
        {
            if (!IsOccupied)
                return Vector2.zero;
            return View.transform.position;
        }

        public Vector2 GetLocalPosition()
        {
            if (!IsOccupied)
                return Vector2.zero;
            return View.transform.localPosition;
        }


        public void Apply()
        {
            if (!IsOccupied)
                return;

            var rect = View.RectTransform;
            rect.sizeDelta = _sizeDelta;
            rect.pivot = _pivot;
            rect.anchorMin = _anchor;
            rect.anchorMax = _anchor;
            rect.localScale = _localScale;
            rect.anchoredPosition = _anchoredPosition;
            rect.localEulerAngles = _localEulerAngles;
        }

        public void UpdateBounds()
        {
            var worldToLocalMatrix = viewport.worldToLocalMatrix;

            UIReuseListTransformation.GetWorldCornersByAnchore(ref corners,
                content,
                _anchoredPosition,
                _sizeDelta,
                _pivot, _anchor, 0);

            _bound = UIReuseListTransformation.GetBounds(corners, ref worldToLocalMatrix, false);
        }

        Vector2 IVirtualLayoutElement.Size => _sizeDelta;

        void IVirtualLayoutElement.SetAnchorPosition(Vector2 anchor, Vector2 anchorPos)
        {
            _pivot = anchor;
            _anchor = anchor;
            _anchoredPosition = anchorPos;
        }
    }
}
